package com.echo.common.utils;

import com.echo.dao.AuthorizationDAO;
import com.echo.entity.bean.AuthorizationEntity;
import com.echo.utils.RedisUtil;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/***
 * @date   2021/7/15 0015 14:06
 * @author JackeyTower
 * 权限控制工具类
 */
@Component
public class AuthorizationUtil {

    private  AuthorizationDAO authorizationDAO;
    private RedisUtil redisUtil;


    public static AuthorizationUtil authorizationUtil;

    public AuthorizationUtil(AuthorizationDAO authorizationDAO, RedisUtil redisUtil) {
        this.authorizationDAO = authorizationDAO;
        this.redisUtil = redisUtil;
    }

    @PostConstruct
    public void init(){
        authorizationUtil=this;
    }


    /**
     * 在需要权限判断的接口处使用，
     * 传入用户的id，返回true即表示用户拥有该接口权限，返回false表示用户无此接口权限
     * @return
     */
    public boolean authorityJudgement(int uid){

        int identityStatus=-1;
        try {
            identityStatus = (int) redisUtil.get("IS_"+uid);
        } catch (NullPointerException e) {
            throw new AuthenticationCredentialsNotFoundException("请重新登录");
        }

        StackTraceElement[] stackTraces = Thread.currentThread().getStackTrace();
        //获取到调用此方法的方法名称
        String methodName = stackTraces[2].getMethodName();
        System.out.println(methodName);

        AuthorizationEntity authorizationEntity = authorizationDAO.selectByRoleAndMethodName(identityStatus,methodName);
        System.out.println(authorizationEntity);

        //判断权限
        if (authorizationEntity!=null){
            return true;
        }

        return false;
    }

}
